<route lang="json5">
{
  style: {
    navigationBarTitleText: '掌上建议',
    enablePullDownRefresh: true, // ✅ 启用下拉刷新
  },
}
</route>

<template>
  <view class="">
    <wd-search
      v-model="searchValue"
      @search="handlesearch"
      hide-cancel
      placeholder="请输入关键字搜索"
      light
    ></wd-search>
    <view class="px-1 py-1 bg-#f5f7f9">
      <view class="px-1 py-1 bg-#f5f7f9">
        <!-- 🔴 空状态提示（列表为空时显示） -->
        <wd-status-tip image="content" tip="暂无意见内容" v-if="!dataList.length" />
        <!-- 🟢 列表循环（列表有数据时显示） -->
        <wd-card v-for="(item, index) in dataList" :key="item.feedbackId" type="rectangle" v-else>
          <template #title>
            <view class="title">
              <view>{{ item.submittedAt }}</view>
              <!--              <view class="flex">
                <view class="mr-2">
                  <wd-button
                    type="text"
                    @click="handleDelete(item.feedbackId)"
                    custom-class="custom-shadow"
                    v-if="canOperate(item)"
                  >
                    删除
                  </wd-button>
                </view>
                <view>
                  <wd-button
                    type="text"
                    @click="handleUpdate(item.feedbackId)"
                    custom-class="custom-shadow"
                    v-if="canOperate(item)"
                  >
                    编辑
                  </wd-button>
                </view>
              </view> -->
            </view>
          </template>
          <view class="content" @click.stop="toDetail(item.feedbackId)">
            <view class="flex">
              <view class="content-sticky" style="">建议</view>
              <view class="mb-12 mt-1 text-16px font-semibold break-words whitespace-normal">
                {{ item.title }}
              </view>
            </view>
            <view class="mb-1">
              {{ item.submitterName }}
            </view>
            <view class="text-#ccc" v-if="showTibetan">
              共收到
              <text>{{ item.replyList?.length }}</text>
              回复
            </view>
            <view v-if="showTibetan">
              <view
                class="text-red text-16px text-center mt-4"
                @click="toDetail(item.feedbackId)"
                v-if="item.replyList?.length > 0 && store.isRepresentative === 1"
              >
                <text class="mr-4">查看回复内容</text>
                <text>></text>
              </view>
            </view>
          </view>
        </wd-card>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import WdStatusTip from 'wot-design-uni/components/wd-status-tip/wd-status-tip.vue'
import { ref, onMounted, nextTick } from 'vue'
import { onLoad, onShow, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import { useMessage, useToast } from 'wot-design-uni'
import {
  IPalmAdviceVo,
  palmAdviceList,
  palmAdviceById,
  createPalmAdvice,
  updatePalmAdvice,
  deletePalmAdvice,
  replyList,
} from '@/api/palmAdvice'
import { useUserStore } from '@/store/user'
import { useTenantStore } from '@/store/tenant'

const store = useUserStore()
const tenantStore = useTenantStore()
const tenant = computed(() => tenantStore.tenantInfo)
const message = useMessage()
const toast = useToast()

const showTibetan = import.meta.env.VITE_SHOW_TIBETAN === 'true'
let isFirstLoad = true // 标志位，避免重复加载
const isLastPage = ref(false)
const isLoading = ref(false) // 避免重复请求

// 查询参数
const pageParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  title: '',
})
//存储数据
const dataList = ref<any>([
  // {
  //   state: 1,
  //   submittedAt: '2025-04-11 18:00:00',
  //   title: '维护老栏建议',
  //   submitterName: '张发财',
  //   reply: 5,
  //   isSticky: 0,
  // },
  // {
  //   state: 1,
  //   submittedAt: '2023-05-13 13:00:00',
  //   title: '环境治理建议',
  //   submitterName: '苍央卓玛',
  //   reply: 2,
  //   isSticky: 0,
  // },
  // {
  //   state: 3,
  //   submittedAt: '2025-05-14 11:00:00',
  //   title: '交通问题建议',
  //   submitterName: '猪猪侠',
  //   reply: 3,
  // },
  // {
  //   state: 2,
  //   submittedAt: '2025-05-16 06:00:00',
  //   title: '河道治理建议',
  //   submitterName: '法外狂徒张三',
  //   reply: 8,
  // },
])
onLoad((options) => {
  pageParams.value.tenantId = tenant.value.tenantId
  pageParams.value.createBy = String(store.userInfo?.userId)
  // 读取本地缓存
  const rid = uni.getStorageSync('representativeId')
  // pageParams.value.representativeId = rid || null
  // ❗用完建议清理，避免缓存残留
  uni.removeStorageSync('representativeId')
  // 首次加载页面时触发
  fetchDataList(true)
  console.log('dataList.value', dataList.value)
  isFirstLoad = false
})

onShow(() => {
  pageParams.value.tenantId = tenant.value.tenantId
  pageParams.value.createBy = String(store.userInfo?.userId)
  // 不是首次时才触发刷新（避免重复请求）
  if (!isFirstLoad) {
    fetchDataList(true) // 传 true 代表刷新模式
  }
})

const searchValue = ref<string>('')

const handlesearch = (val) => {
  // 清空之前的搜索条件
  console.log('val', val)
  pageParams.value.title = val.value
  // 重新获取数据
  fetchDataList(true)
}
const toDetail = (id: number) => {
  console.log('id', id)

  //跳转到详情页面
  uni.navigateTo({ url: `/pages/palmAdvice/detail?id=${id}` })
}
//获取列表数据
const fetchDataList = async (isRefresh = false) => {
  if (isLoading.value || (isLastPage.value && !isRefresh)) return

  isLoading.value = true

  if (isRefresh) {
    pageParams.value.pageNum = 1
    isLastPage.value = false
  }

  try {
    console.log('pageParams.value', pageParams.value)

    const res: any = await palmAdviceList(pageParams.value)
    if (res.code === 0) {
      const total = res.total
      const resultList = res.data || []
      const mappedList = await Promise.all(
        resultList.map(async (item) => {
          let replyListData = []
          if (item.feedbackId && showTibetan) {
            try {
              const replyRes = await replyList(item.feedbackId)
              if (replyRes.code === 0) {
                replyListData = replyRes.data || []
              }
            } catch (err) {
              console.warn('获取回复失败', err)
            }
          }
          return {
            ...item,
            replyList: replyListData,
            status: replyListData.length > 0 ? 1 : 0,
          }
        }),
      )
      if (isRefresh) {
        dataList.value = mappedList
        console.log('dataList.value', dataList.value)
      } else {
        dataList.value = [...dataList.value, ...mappedList]
        console.log('dataList.value', dataList.value)
      }

      // 判断是否是最后一
      const totalPage = Math.ceil(total / pageParams.value.pageSize)
      if (pageParams.value.pageNum >= totalPage) {
        isLastPage.value = true
      } else {
        pageParams.value.pageNum += 1
      }
    }
  } catch (error) {
    console.error(error)
  } finally {
    isLoading.value = false
    if (isRefresh) uni.stopPullDownRefresh() // 停止下拉刷新动画
  }
}
// 封装条件判断方法
const canOperate = (item: any) => {
  if (!store.userInfo?.userId) return false
  return Number(item.status) === 0 && Number(item.createBy) === Number(store.userInfo.userId)
}
//删除操作
const handleDelete = async (id: string | number) => {
  // ✅ 第一步：弹出确认框（防止误操作）
  uni.showModal({
    title: '确认删除', // 确认框标题（可自定义）
    content: '是否确定删除该记录？', // 确认框内容（可根据业务调整，如“删除后不可恢复”）
    cancelColor: '#666', // 取消按钮颜色（可选）
    confirmColor: '#F00', // 确认按钮颜色（可选，强调风险）
    success: async (modalRes) => {
      // ✅ 用户点击“确定”，执行删除逻辑
      if (modalRes.confirm) {
        try {
          uni.showLoading({
            title: '删除中...',
            mask: true, // 蒙版禁止页面交互（关键）
          })
          const res = await deletePalmAdvice({ feedbackId: id })

          if (res.code === 0) {
            // 假设code=0为成功（需匹配接口实际约定）
            uni.showToast({
              title: '删除成功', // 成功提示
              icon: 'success', // 系统默认“对勾”图标（符合用户习惯）
            })
            // 🌟 可选：删除成功后刷新列表（需根据页面逻辑补充，如调用getList()）
            await fetchDataList(true)
          } else {
            uni.showToast({
              title: res.msg || '删除失败',
              icon: 'none',
            })
          }
        } catch (error) {
          // ❌ 捕获异常（如网络错误、接口崩溃）
          console.error('删除失败:', error)
          uni.showToast({
            title: '删除失败，请重试', // 通用错误提示
            icon: 'none',
          })
        } finally {
          // ✅ 第五步：无论成功/失败，关闭加载提示（必须执行）
          uni.hideLoading()
        }
      }
      // ✅ 用户点击“取消”，不执行任何操作（无需处理）
    },
  })
}
//编辑操作
const handleUpdate = (feedbackId: string | number) => {
  uni.navigateTo({
    url: `/pages/palmAdvice/create?id=${feedbackId}`,
  })
}
onPullDownRefresh(() => {
  fetchDataList(true)
})

onReachBottom(() => {
  fetchDataList(false)
})
</script>

<style scoped lang="scss">
.customClass {
  margin: 100px 0;
}

.title {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  color: #000;
}

.content {
  color: #000;
}

.content-sticky {
  color: #fff;
  margin-right: 20rpx;
  background-color: red;
  text-align: center;
  width: 70rpx;
  height: 50rpx;
  font-size: 24rpx;
  line-height: 50rpx;
  border-radius: 10rpx;
  flex-shrink: 0;
}
</style>
